class MonitorSDK {
    constructor() {
      this.endpoint = 'http://192.178.28.40:5102/api/report' // 上报地址
      this.uuid = this.generateUUID()
      this.initAutoPV()
    }
  
    // 生成唯一用户标识
    generateUUID() {
      let uuid = localStorage.getItem('monitor_uuid')
      if (!uuid) {
        uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
          const r = Math.random() * 16 | 0
          return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16)
        })
        localStorage.setItem('monitor_uuid', uuid)
      }
      return uuid
    }
  
    // 自动记录PV
    initAutoPV() {
      window.addEventListener('load', () => this.reportPV())
      
      // 监听SPA路由变化
      const historyPushState = history.pushState
      history.pushState = (...args) => {
        historyPushState.apply(history, args)
        this.reportPV()
      }
    }
  
    // 上报PV
    reportPV() {
      const data = {
        type: 'pv',
        uuid: this.uuid,
        page: window.location.pathname,
        timestamp: Date.now()
      }
      this.send(data)
    }
  
    // 通用上报方法
    send(data) {
      if (navigator.sendBeacon) {
        const blob = new Blob([JSON.stringify(data)], { type: 'application/json' })
        navigator.sendBeacon(this.endpoint, blob)
      } else {
        fetch(this.endpoint, {
          method: 'POST',
          body: JSON.stringify(data),
           credentials: 'include'
        })
      }
    }
  }
  
  // 初始化
  window.monitor = new MonitorSDK()